<template>
  <div class="yxp">
    <div class="yxp-wordList-top">
      <div class="back" id="yxp-before-back" @click="handleBack">
        <span></span>
      </div>
      <span class="yxp-top-c">学前检测</span>
      <div class="yxp-top-r">
        <div class="success">
          <img src="@/assets/word/success-icon.png" />{{successNum}}词
        </div>
        <div class="error">
          <img src="@/assets/word/error-icon.png" />{{errorNum}}词
        </div>
        <div class="btn" id="yxp-before-save" @click="handleSave">开始识记</div>
      </div>
    </div>
    <div class="yxp-word-box" id="wordBox">
    <div class="yxp-wordList-box">
    <div class="yxp-wordList-box-item">
      <div class="yxp-wordList-main">
          <div class="yxp-wordList-item list-item" v-for="(item,i) in dataList" :key="item.id" @click="handlePlay(item,i)">
            <div class="yxp-wordList-item-l" :class="{active: item.num > 0 && curIndex === i}">
              <span class="word-en">{{item.word}}</span>
              <span class="word-zh" v-show="item.num === 2 && curIndex === i">{{item.translate}}</span>
            </div>
            <div class="yxp-wordList-item-r">
              <div class="success img1" v-show="item.isSuccess" :id="'yxp-before-success28-'+item.word" @click.stop="handleSelectSuccess(i,item)"></div>
              <div class="success img2" v-show="!item.isSuccess" :id="'yxp-before-success29-'+item.word" @click.stop="handleSelectSuccess(i,item)"></div>
              <div class="success img3" v-show="!item.isError" :id="'yxp-before-error30-'+item.word"  @click.stop="handleSelectError(i,item)"></div>
              <div class="success img4" v-show="item.isError" :id="'yxp-before-error31-'+item.word"  @click.stop="handleSelectError(i,item)"></div>
            </div>
          </div>
        </div>
      
      <div class="yxp-wordList-page btn-hover" @click="handleNext" id="yxp-before-study" v-if="this.pageIndex < this.page">提交本页数据，并进入下一页</div>
      </div>
    </div>
    </div>
      <Timetips ref="timetips"></Timetips>
    <audio ref="audio"></audio>
    <div class="yxp-wordList-mark" v-if="isShow"></div>
    <div class="yxp-before-pop" v-if="isShow">
      <div class="close" @click="handleClose">
      </div>
      <p class="text text-one">认识的词点击对勾，标记为<img src="@/assets/word/success.png" /></p>
      <p class="text">不熟悉的点击叉号，标记为<img src="@/assets/word/error-sel.png" /></p>
      <p class="tips">点击[开始识记]后会把标记红叉的单词进行识记学习</p>
      <div class="btn" id="yxp-know" @click="handleClose">知道了</div>
    </div>
    <div class="mark" v-if="isShow || isBack"></div>
    <div class="yxp-wordList-pop" v-if="isBack">
      <div class="close" @click="isBack = false"></div>
      <!-- <img src="@/assets/word/close-icon.png" class="close" @click="isBack = false"/> -->
      <p class="tips">是否放弃选词</p>
      <div class="btn">
        <span class="btn-item" @click="handleSure" id="yxp-before-sure">确定</span>
        <span class="btn-item" @click="isBack = false" id="yxp-before-reset">取消</span>
      </div>
    </div>
  </div>
</template>
<script>
import { distingUishword, reciteword, printList, middleStop,doubleminusdistinguiShword } from  '@/services/word.js'
import storage from '@/utils/storage.js'
import Timetips from "@/components/Timetips";
export default {
  name: 'beforeStudy',
  components: {
    Timetips
  },
  data() {
    return {
      isShow: true,
      isBack: false,
      isNext: true,
      isPrint: false,
      study_model: -1,
      package_id: -1,
      course_type: 0,
      pageSize: 20,
      pageIndex: 1,
      total: 0,
      page: 0,
      initData: [],
      dataList:  [],
      canArr: [],
      canSub: [],
      canNotArr: [],
      checkData: [],
      successNum: 0,
      errorNum: 0,
      is_doubleminus:sessionStorage.getItem('doubleminus_type'),
    }
  },
  destroyed () {
    delete window.__LIMIT_TIME__
  },
  beforeDestroy() {
    this.$refs.timetips.stopTimer();
    this.$refs.timetips.stopEndTimer();
  },
  created () {
    window.__LIMIT_TIME__ = -1
    if (this.$route.query) {
      let query = this.$route.query
        this.study_model = query.study_model
        this.package_id = query.package_id,
        this.course_type = +query.course_type
        this.total = query.total
        this.page = Math.ceil(this.total / this.pageSize)
    }
    let data = JSON.parse(window.localStorage.getItem('beforeWord'))
    data.map(item => {
      item.num = 0
      item.isSuccess = false
      item.isError = false
    })
    this.dataList = data
  },
  methods: {
    // 提交下页面数据
    handleNext () {
      if (this.course_type === 1) {
        if (this.errorNum + this.successNum < this.dataList.length * this.pageIndex) {
          this.$toast('当前页还没选完，不能进入下一页~')
          return
        }
      }
      this.pageIndex++
      if (this.canArr.length > 0) {
        this.distingSave()
      } else {
        this.getReciteWord()
      }
      let scrollDom = document.getElementById('wordBox')
      scrollDom.scrollTop = 0
    },
    handleSave () {
      if (this.canArr.length === 0 && this.canNotArr.length === 0) {
        this.$toast('还没有选词哦~')
        return
      }
      if (this.canNotArr.length > 0) {
        if (!this.isPrint) {
          this.isPrint = true
          this.handlePrint()
          setTimeout(() => {
            this.isPrint = false
          }, 60000);
        } else {
          this.$toast('60s内不能频繁打印~')
        }
      } 
      else {
        this.SaveWord()
      }
     
    },
    async handlePrint () {
      // localStorage.setItem('dataList', JSON.stringify(this.checkData))
      this.$loading.show()
      let page = Math.ceil(this.checkData.length / 5)
      let wordData = []
      for (let i = 0; i < page; i++) {
        let start = i * 5
        let end = (i + 1) * 5
        let data = this.checkData.slice(start, end)
        let obj = {
          page: i + 1,
          status: false,
          isEnd: false,
          isCheck: false,
          data: data
        }
        wordData.push(obj)
      }
      storage.set('paperData',wordData)
      // window.localStorage.setItem('paperData', JSON.stringify(wordData))
      // window.localStorage.setItem('dataList', JSON.stringify(this.checkData))
      let params = {
        question_type: 0,
        word_list: this.canNotArr.join(','),
        from: 'word_remember',
        package_id: this.package_id
      }
      try {
        let data = await printList(params)
        if (data.code === 1) {
          this.$toast('已选单词已提交后台打印')
          this.SaveWord()
        }
      } catch {
        this.$loading.hide()
      }

    },
    // 一眼会识记
    async SaveWord () {
      this.$loading.show()
      let params = {
        can: this.canArr.join(','),
        can_not: this.canNotArr.join(','),
        type: 'init',
        package_id: this.package_id,
        times: 1,
        f_type: 1
      }
      try {
        let data = '';
        // if(this.is_doubleminus == 1){
        //   data = await doubleminusdistinguiShword(params)
        // }else {
          data = await distingUishword(params)
        // }
        if (data.code === 1) {
          if (this.canNotArr.length === 0) {
            if (data.data.is_finish === 1) {
              if(data.data.complete >= 3){
                this.$router.push({
                  path: '/wordRemember/wordReport',
                  query: {
                    id: data.data.resid,
                    is_finish:data.data.is_finish,
                    type:1,
                    content:data.data.content
                  }
                })
              }else{
                this.$router.push({
                  path: '/wordRemember/wordGrade',
                  query: {
                    path: window.encodeURIComponent(data.data.url),
                    package_id: this.package_id,
                    is_finish:data.data.is_finish,
                    title: this.$route.query.title
                  }
                })
              }
            } else {
              this.$router.replace({
                path: '/wordRemember'
              })
            }
          } else {
            this.$router.push({
              path: '/wordRemember/wordMemory',
              query: {
                package_id: this.package_id,
                course_type: this.course_type
              }
            })
          }
        } else if (data.code === '10001' || data.code === 10001) {
          this.$loading.hide()
          this.$toast('token过期，请重新登录')
        } else {
          this.$loading.hide()
          this.$toast(data.info)
        }
      } catch {
        this.$loading.hide()
      }

    },
    // 一眼会
    async distingSave () {
      this.$loading.show()
      let params = {
        can: this.canArr.join(','),
        type: 'init',
        f_type: '0',
        package_id: this.package_id,
        times: 1
      }
      let data = '';
      // if(this.is_doubleminus == 1){
      //   data = await doubleminusdistinguiShword(params)
      // }else {
        data = await distingUishword(params)
      // }
      if (data.code === 1) {
        this.canArr = []
        this.getReciteWord()
      } else if (data.code === '10001' || data.code === 10001) {
        this.$loading.hide()
        this.$toast('token过期，请重新登录')
      } else {
        this.$loading.hide()
        this.$toast(data.info)
      }
    },
    async getReciteWord () {
      this.$loading.show()
      let params = {
        package_id: this.package_id,
        page: this.pageIndex
      }
      let data = await reciteword(params)
      if (data.code === 1) {
        this.$loading.hide()
        data.data.to_study.map(item => {
          item.num = 0
          item.isSuccess = false
          item.isError = false
        })
        this.dataList = data.data.to_study
        this.total = data.data.total
        this.page = Math.ceil(this.total / this.pageSize)
      } else if (data.code === '10001' || data.code === 10001) {
        this.$loading.hide()
        this.$toast('token过期，请重新登录')
      } else {
        this.$loading.hide()
        this.$toast(data.info)
      }
    },
     // 播放语音
    handlePlay (item, i) {
      console.log(111)
      this.curIndex = i
      let num = item.num
      num++
      if (num > 2) num = 1
      this.$set(item, 'num', num)
      let audio = this.$refs.audio
      audio.src = item.project_voice
      audio.play().then((r)=>{}).catch((e)=>{})
      this.dataList.map((elem,index) => {
        if (index !== i) {
          this.$set(elem, 'num', 0)
        }
      })
    },
    handleSelectSuccess (i, item) {
      if (item.isSuccess) return
      this.successNum++
      let obj = this.dataList[i]
      this.$set(obj, 'isError', false)
      this.$set(obj, 'isSuccess', true)
      let index = this.checkData.findIndex(elem => {
        return elem.id === item.id
      })
      if (index > -1) {
        this.checkData.splice(index,1)
      }
      if (this.canArr.indexOf(item.id) === -1) {
        this.canArr.push(item.id)
      }
      if (this.canNotArr.indexOf(item.id) > -1) {
        let index = this.canNotArr.indexOf(item.id)
        this.canNotArr.splice(index, 1)
        this.errorNum--
      }
    },
    handleSelectError (i, item) {
      if (item.isError) return
      if (this.canNotArr.length === 45) {
        this.$toast('单词已选够45个了，开始识记把~')
        return
      }
      this.errorNum++
      this.checkData.push(item)
      let obj = this.dataList[i]
      this.$set(obj, 'isSuccess', false)
      this.$set(obj, 'isError', true)
      if (this.canNotArr.indexOf(item.id) === -1) {
        this.canNotArr.push(item.id)
      }
      if (this.canArr.indexOf(item.id) > -1) {
        let index = this.canArr.indexOf(item.id)
        this.canArr.splice(index, 1)
        this.successNum--
      }
    },
    handleClose () {
      this.isShow = false
    },
    handleBack () {
      this.isBack = true
    },
    async handleSure () {
      if (this.course_type === 1) {
		// this.$loading.hide()
		this.$router.replace({
			path: '/wordRemember'
		})
        // this.$loading.show()
      //   let data = await middleStop({ id: this.package_id, question_type: '0'})
      //   if (data.code === 1) {
      //     this.$loading.hide()
      //     this.$router.replace({
      //       path: '/wordRemember'
      //     })
      //   } else if (data.code === '10001' || data.code === 10001) {
      //   this.$loading.hide()
      //   this.$toast('token过期，请重新登录')
      // } else {
      //   this.$loading.hide()
      //   this.$toast(data.info)
      // }
      } else {
        this.$router.replace({
          path: '/wordRemember'
        })
      }
    }
  },
}
</script>
<style lang="less" scoped>
.before-word {
  padding-bottom: 60px;
}
.yxp-wordList-top {
  .back {
    position: absolute;
    left: 40px;
    top: 27px;
    width: 30px;
    height: 27px;
    cursor: pointer;
  }
  .yxp-top-r {
    position: absolute;
    right: 40px;
    top: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    .success {
      font-size: 20px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #27BFA3;
      margin-right: 29px;
      img {
        width: 20px;
        height: 14px;
        display: inline-block;
        vertical-align: middle;
        margin-right: 10px;
      }
    }
    .error {
      font-size: 20px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #FF6767;
      margin-right: 50px;
      img {
        width: 18px;
        height: 18px;
        display: inline-block;
        vertical-align: middle;
        margin-right: 10px;
      }
    }
    .btn {
      width: 140px;
      height: 46px;
      line-height: 46px;
      font-size: 20px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      color: #fff;
      background:linear-gradient(360deg,rgba(71,203,179,1) 0%,rgba(81,211,176,1) 100%);
      box-shadow:0px 5px 10px rgba(59,201,164,0.3);
      border-radius: 30px;
      cursor: pointer;
      &:hover {
        background:linear-gradient(360deg,rgba(39,178,152,1) 0%,rgba(52,203,163,1) 100%);
        box-shadow:0px 5px 10px rgba(59,201,164,0.3);
      }
    }
  }
}

.yxp-wordList-page {
  width: 360px;
  height: 60px;
  line-height: 60px;
  font-size: 24px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #fff;
  background:linear-gradient(360deg,rgba(71,203,179,1) 0%,rgba(81,211,176,1) 100%);
  box-shadow:0px 5px 10px rgba(59,201,164,0.3);
  border-radius: 10px;
  margin: 40px auto;
  cursor: pointer;
  &:hover {
    background:linear-gradient(360deg,rgba(39,178,152,1) 0%,rgba(52,203,163,1) 100%);
  }
  &:active {
    background:linear-gradient(180deg,rgba(71,203,179,1) 0%,rgba(81,211,176,1) 100%);
  }
}
.yxp-wordList-mark {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,.5);
}
.yxp-before-pop {
  position: fixed;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
  width: 480px;
  height: 355px;
  text-align: center;
  background: #fff;
  border-radius: 20px;
  z-index: 1000;
   .close {
      position: absolute;
      right: 20px;
      top: 15px;
      width: 20px;
      height: 20px;
      background: url(../../../assets/word/close-icon.png) no-repeat;
      background-size: 20px 20px;
      cursor: pointer;
      &:hover {
        background-image: url(../../../assets/word/close-hover.png);
      }
    }
  .text-one {
    margin-top: 59px;
    margin-bottom: 19px;
  }
  .text {
    font-size: 24px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #333333;
    img {
      width: 30px;
      height: 30px;
      margin-left: 10px;
      vertical-align: middle;
    }
  }
  .tips {
    font-size: 18px;
    font-family: Source Han Sans CN;
    font-weight: 400;
    color: #999;
    margin-top: 30px;
  }
  .btn {
    width: 350px;
    height: 50px;
    line-height: 50px;
    text-align: center;
    font-size: 18px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #fff;
    background: #27BFA3;
    border-radius: 100px;
    margin: 40px auto 0;
    cursor: pointer;
    &:hover {
      background: #18A38A;
    }
  }
}
</style>
